// src/hooks/useDevice.ts
import { ref, computed } from 'vue';
import {
  getDeviceNameByCode,
  getDeviceInfoByCode,
  flattenDeviceTree,
  getDeviceNameFromMap
} from '@/utils/deviceUtils';

/**
 * 设备相关的 Composable
 */
export const useDevice = (deviceTreeData: any[] = []) => {
  const treeData = ref(deviceTreeData);

  // 扁平化的设备映射，用于快速查找
  const deviceMap = computed(() => flattenDeviceTree(treeData.value));

  /**
   * 设置设备树数据
   */
  const setDeviceTreeData = (data: any[]) => {
    treeData.value = data;
  };

  /**
   * 根据 deviceCode 查找设备名称
   */
  const getDeviceName = (deviceCode: string): string => {
    // 使用扁平化映射快速查找（性能更好）
    return getDeviceNameFromMap(deviceCode, deviceMap.value);
  };

  /**
   * 根据 deviceCode 查找完整设备信息
   */
  const getDeviceInfo = (deviceCode: string): any => {
    return getDeviceInfoByCode(deviceCode, treeData.value);
  };

  /**
   * 批量获取设备名称
   */
  const getDeviceNames = (deviceCodes: string[]): Record<string, string> => {
    const result: Record<string, string> = {};
    deviceCodes.forEach(code => {
      result[code] = getDeviceName(code);
    });
    return result;
  };

  return {
    treeData,
    deviceMap,
    setDeviceTreeData,
    getDeviceName,
    getDeviceInfo,
    getDeviceNames
  };
};

export default useDevice;
